package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.mapper.MenuMapper;
import com.example.demo.mapper.RoleMapper;
import com.example.demo.mapper.RoleMenuMapper;
import com.example.demo.pojo.Menu;
import com.example.demo.pojo.RoleMenu;
import com.example.demo.pojo.User;
import com.example.demo.utils.LayuiResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/menu")
public class EndMenuController {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Autowired
    private MenuMapper menuMapper;


    /**
     * 获取登陆用户菜单权限
     * @param id
     * @param request
     * @return
     */
    @RequestMapping("/getByUserId/{id}")
    public Object getByUserId(@PathVariable Integer id, HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("user");
        return LayuiResult.LayuiData(0,"success",getMenuByRole(user.getRoleId()));
    }

    /**
     * 权限管理查询选中角色的所有权限
     * @param id
     * @return
     */
    @RequestMapping("/getByUserRoleMenu/{id}")
    public Object getByUserRoleMenu(@PathVariable Integer id){
        return LayuiResult.LayuiData(0,"success",getMenuByRole(id));
    }


    /**
     * 通过父id查询子菜单节点
     * @param id
     * @return
     */
    @RequestMapping("/get/child/{id}")
    public Object getChild(@PathVariable Integer id){
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",id);
        List<Menu> menus = menuMapper.selectList(queryWrapper);
        return LayuiResult.LayuiData(0,"success",menus);
    }

    /**
     * 添加菜单权限
     * @param menu
     * @return
     */
    @RequestMapping("/add")
    public Object add(@RequestBody Menu menu){
        menuMapper.insert(menu);
        return LayuiResult.LayuiData(0,"添加权限菜单成功",null);
    }


    /**
     * 获取所有菜单节点
     * @param page
     * @param limit
     * @return
     */
    @RequestMapping("/get")
    public Object get(Integer page,Integer limit){
        PageHelper.startPage(page,limit);
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        List<Menu> menus = menuMapper.selectList(queryWrapper);
        Integer count = menuMapper.selectCount(queryWrapper);
        PageInfo<Menu> pageInfo = new PageInfo<>(menus);
        return LayuiResult.LayuiData(0,"success",pageInfo.getList(),count);
    }


    /**
     * 获取父菜单节点
     * @return
     */
    @RequestMapping("/get/parent")
    public Object getParent(){
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",0);
        List<Menu> menus = menuMapper.selectList(queryWrapper);
        return LayuiResult.LayuiData(0,"success",menus);
    }


    /**
     * 删除菜单节点
     * @param id
     * @return
     */
    @RequestMapping("/delete/{id}")
    public Object delete(@PathVariable Integer id){
        Menu menu = new Menu();
        menu.setId(id);
        menu.setStatus(1);
        menuMapper.updateById(menu);
        return LayuiResult.LayuiData(0,"删除成功",null);
    }

    /**
     * 恢复删除
     * @param id
     * @return
     */
    @RequestMapping("/back/{id}")
    public Object back(@PathVariable Integer id){
        Menu menu = new Menu();
        menu.setId(id);
        menu.setStatus(0);
        menuMapper.updateById(menu);
        return LayuiResult.LayuiData(0,"恢复成功",null);
    }

    /**
     * 修改菜单节点
     * @param menu
     * @return
     */
    @RequestMapping("/update")
    public Object update(@RequestBody Menu menu){
        menuMapper.updateById(menu);
        return LayuiResult.LayuiData(0,"修改成功",null);
    }


    /**
     * 查询登录用户所有菜单权限
     * @param id
     * @return
     */
    public Object getMenuByRole(Integer id){
        QueryWrapper<RoleMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id",id);
        List<RoleMenu> roleMenus1 = roleMenuMapper.selectList(queryWrapper);
        List<Menu> menuParent = new ArrayList<>();
        roleMenus1.forEach(roleMenu -> {
            Menu menu = menuMapper.selectById(roleMenu.getMenuId());
            if(menu.getParentId() == 0){
                menuParent.add(menu);
            }
        });
        /*MenuExample me = new MenuExample();
        me.createCriteria().andParentIdEqualTo(0);*/
        List<Map<String, Object>> listResult = new ArrayList<>();
        menuParent.forEach(menu -> {
            Map<String,Object> map = new HashMap<>();
            map.put("title",menu.getMenuName());
            map.put("menuName",menu.getMenuName());
            map.put("menuUrl",menu.getMenuUrl());
            map.put("id",menu.getId());
            QueryWrapper<Menu> menuQueryWrapper = new QueryWrapper<>();
            menuQueryWrapper.eq("parent_id",menu.getId()).eq("status",1);
            List<Menu> menuChild = menuMapper.selectList(menuQueryWrapper);
            List<Integer> list = new ArrayList<>();
            menuChild.forEach(menuInt -> {
                list.add(menuInt.getId());
            });
            QueryWrapper<RoleMenu> roleMenuQueryWrapper = new QueryWrapper<>();
            roleMenuQueryWrapper.eq("role_id",id).in("menu_id",list);
            List<RoleMenu> roleMenus = roleMenuMapper.selectList(roleMenuQueryWrapper);
            List<Map<String,Object>> listChildMap = new ArrayList<>();
            roleMenus.forEach(childRoleMenu -> {
                Map<String,Object> childMap = new HashMap<>();
                Menu menuChildObj = menuMapper.selectById(childRoleMenu.getMenuId());
                childMap.put("title",menuChildObj.getMenuName());
                childMap.put("menuName",menuChildObj.getMenuName());
                childMap.put("menuUrl",menuChildObj.getMenuUrl());
                childMap.put("id",menuChildObj.getId());
                listChildMap.add(childMap);
            });
            map.put("children",listChildMap);
            listResult.add(map);
        });
        return listResult;
    }

}
